package main

import (
	"encoding/json"
	// "time"
	"log"

	"github.com/astaxie/beego/orm"

	"dzomc/controllers"
	"dzomc/models"
	"dzomc/tcp"
	"encoding/hex"
)

type EchoCallback struct{}

func (ec *EchoCallback) OnConnected(conn *tcp.TCPConn) {
	log.Println("new conn: ", conn.GetRemoteAddr())
}

//收到信息处理
//lora协议格式，两种类型封装成一个不知道有没有问题
/*
case 'T': //时基信息 src_id(2),type(1),msg_len(1),utc(4),flag(1),sender_id(2),sender_utc(4),flag(1),slot(4),status(4),fcs(1);
		//00 01 54 19 59 66 bf 20 00 00 01 59 66 bf 20 00 00 00 00 02 00 00 00 00 4f

case 'R': //固定台信息 src_id(2),type(1),msg_len(1),utc(4),flag(1),sender_id(2),sender_utc(4),flag(1),speed(2),direct(1),fcs(1)

12480   RX   : 170601_143404  info:00 02 52 14 59 2F B5 5B 00 00 03 59 2F B4 B1 00 00 AA 00 06
12481   RX   : 170601_143404  info:00 02 52 14 59 2F B5 5B 00 00 02 59 2F B5 5B 00 00 AA 00 EC
12482   RX   : 170601_143237  info:00 06 54 19 59 2F B4 FA 00 00 02 59 2F B4 99 00 00 00 DD 7C 00 00 00 00 8B
12483   RX   : 170601_143237  info:00 06 54 19 59 2F B4 FA 00 00 03 59 2F B4 B1 00 00 00 DD 78 00 00 00 00 A6
*/

// type LoraPacket struct {
// 	src_id      uint16
// 	cmd         uint8
// 	len         uint8
// 	utc         uint32
// 	flag        byte
// 	sender_id   uint16
// 	sender_utc  uint32
// 	sender_flag byte
// 	slot        uint32
// 	status      uint32
// 	speed       uint16
// 	direct      byte
// 	fcs         byte
// }

//收到信息存入数据库
//websocket转发
func (ec *EchoCallback) OnMessage(conn *tcp.TCPConn, p tcp.Packet) {
	dat := p.Bytes()
	hexinfo := hex.EncodeToString(dat)
	log.Println("hexdump>", hexinfo)

	o := orm.NewOrm()
	lora_rec := new(models.LoraRecord)
	lora_rec.Ipaddr = conn.GetRemoteAddr().String()
	lora_rec.SrcId = uint16(dat[0])<<8 | uint16(dat[1])
	// lora_rec.Accept=time.Now()
	lora_rec.Cmd = dat[2]
	lora_rec.Info = hexinfo
	_, err := o.Insert(lora_rec)
	if err != nil {
		log.Println(err)
	}

	jsonstr, _ := json.Marshal(&lora_rec)
	msg := controllers.Message{Category: "TCP", Sender: lora_rec.Ipaddr, Content: string(jsonstr)}
	controllers.WsBroadcast(msg)

	// conn.AsyncWritePacket(p)
}
func (ec *EchoCallback) OnDisconnected(conn *tcp.TCPConn) {
	log.Printf("%s disconnected\n", conn.GetRemoteIPAddress())
}

func (ec *EchoCallback) OnError(err error) {
	log.Println(err)
}
